/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.QuickTips.init();
var _pageSize = 20;

var fieldName = ['id', 'name', 'note', 'status', 'orgCode'];
var fieldLabel = ['ID', '名称', '备注', '状态', '机构编码'];

var saveServlet = '../../servlet/system/RoleSave';
var loadServlet = '../../servlet/system/RoleLoad';
var deleteServlet = '../../servlet/system/RoleDel';

var theme = '角色';
var _pageSize = 20;
var _title = currentOrgName + " " + theme + '管理';


var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: fieldName[0],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[0],
                    hidden: true
                }, {
                    name: fieldName[1],
                    id: fieldName[1],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[1],
                    allowBlank: true
                }, {
                    name: fieldName[2],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[2],
                    width: 150
                }, {                   
                    xtype: 'textfield',
                    fieldLabel: "所属单位",
                    width: 150,
                    value: currentOrgName,
                    //disable:true,
                    readOnly: true
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime(); 
                        submitConfig.params.token=token;
                        submitConfig.params.token1=token1;
                        if (type === 1)
                            submitConfig.params.cmd = 'create';
                        else {
                            submitConfig.params.id = checkboxSel.getSelected().get("id");
                            submitConfig.params.cmd = 'update';
                        }
                        Ext.getCmp('input-form').getForm().submit(submitConfig);

                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);
var win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});
var vroot = new Ext.tree.TreeNode({
    text: '主菜单',
    draggable: false,
    id: '01',
    checked: true,
    expanded: true,
    leaf: false
});

var vloader = new Ext.tree.TreeLoader({url: "../../servlet/system/RoleMenuTreeServlet"});
vloader.on('beforeload', function(loader, node) {
        loader.baseParams.id = node.id;
        loader.baseParams.roleId=checkboxSel.getSelected().get("id");
    });

var treeMenu = new Ext.tree.TreePanel({
    //title: '菜单结构', //机构树
    id: 'MenuTree',
    useArrows: true,    
    autoScroll: true,
    animate: true,
    enableDD: false,
    containerScroll: true,
    loadMask: true,
    //width: 500,
    height: 350,
    rootVisible: false,
    collapsed: false,
    collapsible: false,
    split: true,
    //region: 'west',
    checked: true,
    //columnWidth: .4,
    root: vroot,
    loader: vloader
});

/*treeMenu.on('click', function(node) {
 currentRoleCode = node.id;
 currentRoleName = node.text;
 //alert(currentMenuName);
 //  grid.setTitle(currentMenuName + " " + theme + '管理');
 store.load({params: {currentRoleCode: currentRoleCode, start: 0, limit: _pageSize}});
 node.checked = true;
 });*/


var deep = 0;

//选择所有的子结点
function selectAllDescendants(node, checked) {

    for (var i = 0; i < node.childNodes.length; i++) {
        var child = node.childNodes[i];
        //alert(child);
        child.ui.toggleCheck(checked);
        child.attributes.checked = checked;
        //deep++;
        //alert("aaasssss"+deep);
        selectAllDescendants(child,checked);
        //deep--;
    }
}
treeMenu.on('checkchange', function(node, checked) {

    //node.expand = true;
    treeMenu.suspendEvents(false);
    //alert(node.attributes.checked);
    node.attributes.checked = checked;
    /*node.eachChild(function(child)
     {
     child.ui.toggleCheck(checked);
     child.attributes.checked = checked;
     child.fireEvent('checkchange', child, checked);
     });*/
    //alert("oooooooooooooo"+node.text);
    selectAllDescendants(node, checked);
    var parent = node.parentNode;
    while (parent.parentNode) {
        //alert(parent.attributes.text);
        //alert("ppppppp");
        if (checked) {                  //勾选所有双亲
            if (!parent.attributes.checked) {
                parent.ui.toggleCheck(checked);
                //alert("ok");
                parent.attributes.checked = checked;
            }
        } else {
            //先注释掉，因为去掉所有按钮勾选后，不一定要取消其双亲的勾选，因为不能增删改的话，还可以浏览
            /*var flag = true;            //检查所有子结点是否勾选，若所有子结点都不勾选，在其双亲也不勾选。若有子结点勾选，则双亲必勾选
            //console.log('false checked');
            //alert(parent.childNodes+188);
            //alert(parent.childNodes.length);
            for (var i = 0; i < parent.childNodes.length; i++) {
                alert(parent.childNodes[i] + i);
                if (parent.childNodes[i].attributes.checked) {
                    flag = false;
                    break;
                }
            }
            if (flag && parent.attributes.checked) {
                parent.ui.toggleCheck(checked);
                parent.attributes.checked = checked;
            }*/
        }
        parent = parent.parentNode;
    }
    treeMenu.resumeEvents();
});



var win2 = new Ext.Window({
    title: '角色菜单分配',
    width: 500,
    Height: 400,
    layout: 'fit',
    modal: true,
    closeAction: 'hide',
    items: [treeMenu],
    buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function() {

                var menuCodes = '';
                function getAllMenuCodes(root) {
                    if(root.attributes.checked)
                        menuCodes += root.id + ",";
                    for (var i = 0; i < root.childNodes.length; i++) {
                        getAllMenuCodes(root.childNodes[i]);
                    }
                };
                getAllMenuCodes(treeMenu.getRootNode());
                var record = checkboxSel.getSelected();
                var roleId = record.get('id');
                //alert(roleId + ":" + menuCodes);
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: '../../servlet/system/RoleAllocationSave', //提交的删除地址
                    params: {token:token,token1:token1,roleId: roleId, menuCodes: menuCodes},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功保存！");
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }
                        } else {
                            Ext.MessageBox.alert("提示", "所选记录保存失败！");
                        }
                    }
                });
            }
        }, {
            text: '取消',
            handler: function() {
                win2.hide();
            }
        }]
});
var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
function addnew() {
    if (win === null) {
        win = new Ext.Window({
            layout: 'form',
            width: 340,
            autoHeight: true,
            closeAction: 'hide',
            items: []
        });
    }
    type = 1;
    win.setTitle('增加' + theme);
    //if (updated)
    // Ext.getCmp('addusr-form').getForm().getEl().dom.reset();
    Ext.getCmp('input-form').getForm().reset();
    //Ext.getCmp(fieldName[4]).setValue(currentOrgCode);
    win.show();
    //loginForm.form.reset();

    //Ext.getCmp('code').enable();    
}

function update() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                items: [inputForm]
            });
        }

        //alert(checkboxSel.getSelected().get('code'));
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        //Ext.Msg.alert("a",Ext.getCmp("code"));
        //Ext.getCmp('code').readOnly=true;
        //Ext.getCmp('YesNo').setValue(checkboxSel.getSelected().get("ismine"));

        //alert(str);
        //alert(Ext.getCmp('checkdate'));


        win.setTitle('修改' + theme);
        win.show();
        //Ext.getDom('win-title').innerHTML='修改监控设备信息';
    }
}

function remove() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("修改" + theme, "您还没有选择，需要先选择才能删除");
    }
    else {
        Ext.MessageBox.confirm('提示', '确实要删除所选的记录吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var conn = new Ext.data.Connection();
                var token1 = new Date().getTime();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                store.reload(); //重新load数据   	

                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}
//角色菜单分配
function allocation() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("修改" + theme, "您还没有选择，需要先选择才能删除");
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        //vroot.reload();
        //Ext.getCmp('MenuTree').getNodeById('01').reload();
        
        //treeMenu.getLoader().load(vroot,function(){treeMenu.expandAll()});
        treeMenu.getLoader().load(vroot);
        //treeMenu.expandAll();
        //treeMenu.collapseAll();
        win2.show();
    }

}

var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
        ,baseParams:{start:0,limit:_pageSize}
        ,autoLoad:true
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: fieldLabel[1], width: 100, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 100, sortable: true, dataIndex: fieldName[2]},
            {header: fieldLabel[3], width: 100, sortable: true, dataIndex: fieldName[3], hidden: true},
            {header: fieldLabel[4], width: 100, sortable: true, dataIndex: fieldName[4], hidden: true}

        ],
        //autoExpandColumn: fieldName[2],
        
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addnew},
            '-',
            {text: '修改', iconCls: 'icon-edit', handler: update},
            '-',
            {text: '删除', iconCls: 'icon-delete', handler: remove},
            '-',
            {text: '菜单分配', iconCls: 'icon-edit', handler: allocation}
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        })
    });
    //grid.el.center();
    //store.load({params: {start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);

